package com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by wcy on 2017\6\28 0028.
 */

public class SinaLogin extends Activity {
    private static long sClickTime;
    LoadingDialog mLoadingDialog;
    public static void login(Context context) {
        if (UserUtils.isLogin()) {
            return;
        }
        if (System.currentTimeMillis() - sClickTime < 500) {
            return;
        }
        sClickTime = System.currentTimeMillis();
        Intent intent = new Intent(context, SinaLogin.class);
        context.startActivity(intent);
    }

    private SsoHandler mSsoHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WbSdk.install(this, new AuthInfo(this, getString(R.string.sina_app_id), getString(R.string.sina_redirect_url), getString(R.string.sina_scope)));
        mLoadingDialog = new LoadingDialog(this, "正在加载中");
        EventBus.getDefault().register(this);
        startLogin();
    }

    private void getSinaUserInfo(final Oauth2AccessToken token) {
        RetrofitHelper helper = RetrofitHelper.getInstance();
        //helper.setRetrofit(new SinaRetorfit());
        BaseRequestParams params = new BaseRequestParams();
        Map<String, String> map = new HashMap<>();
        map.put("access_token", token.getToken());
        map.put("uid", token.getUid());
        helper.createService(SinaRetorfit.class, ThirdService.class).getWbUserInfo(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
            }
            @Override
            public void onNext(ResponseBody responseBody) {
                String jsonStr = null;
                try {
                    jsonStr = responseBody.string();
                    if (jsonStr != null) {
                        JSONObject jsonObject;
                        try {
                            jsonObject = new JSONObject(jsonStr);
                            String nickname = jsonObject.optString("name");
                            String headimgurl = jsonObject.optString("profile_image_url");
                            StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME,Constants.NICK_NAME, nickname);
                            StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME,Constants.HEADER_IMG, headimgurl);
                        }catch (JSONException e) {
                            e.printStackTrace();
                        }
                        BindRequestParams params = new BindRequestParams();
                        params.openid = token.getUid();
                        params.access_token = token.getToken();
                        params.type = Constants.TYPE_LOGIN_BY_SINA;
                        BindHelper.bind(params);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
            }
            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // SSO 授权回调
        // 重要：发起 SSO 登录的 Activity 必须重写 onActivityResults
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    private void startLogin() {
        mLoadingDialog.show();
        mSsoHandler = new SsoHandler(this);
        mSsoHandler.authorize(new SelfWbAuthListener());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLoadingDialog.dismiss();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void handleBindEvent(BindEvent event) {
        mLoadingDialog.dismiss();
        finish();
    }

    class SelfWbAuthListener implements WbAuthListener {
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (token.isSessionValid()) {
                        AccessTokenKeeper.writeAccessToken(SinaLogin.this, token);
                        //ToastUtil.showMessage(Xutils.getContext(), "授权成功");
                        getSinaUserInfo(token);
                    } else {
                        // 以下几种情况，您会收到 Code：
                        // 1. 当您未在平台上注册的应用程序的包名与签名时；
                        // 2. 当您注册的应用程序包名与签名不正确时；
                        // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                    }
                }
            });
        }
        @Override
        public void cancel() {
            //ToastUtil.showMessage(Xutils.getContext(), "取消授权");
            finish();
        }
        @Override
        public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
            ToastUtil.showMessage(Xutils.getContext(), wbConnectErrorMessage.getErrorMessage());
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }

}
